package com.cobo.fitness.core.entrypoint;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.IService;
import com.cobo.common.core.Page;
import com.cobo.common.core.R;
import com.cobo.fitness.core.SpringContextUtils;
import com.cobo.fitness.web.fitness.vo.DictVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.util.List;
import java.util.Map;

public class HttpApi {

    private static Integer getIntParam(HttpServletRequest request, String key, Integer defaultVal) {
        String val = request.getParameter(key);
        if (val == null) {
            return defaultVal;
        }
        return Integer.parseInt(val);
    }

    private static String getStrParam(HttpServletRequest request, String key, String defaultVal) {
        String val = request.getParameter(key);
        if (val == null) {
            return defaultVal;
        }
        return val;
    }

    private static String lowerHeadName(String name) {
        return StringUtils.substring(name, 0, 1).toLowerCase()
                + StringUtils.substring(name, 1);
    }

    public static <T> R<?> handler(Class<T> claz, Map<String,Object> params, HttpServletRequest request, HttpServletResponse response) {

        String requestURI = request.getRequestURI();
        String serviceBeanName = lowerHeadName(claz.getSimpleName()) + "ServiceImpl";
        IService<T> baseService = (IService<T>)SpringContextUtils.getBean(serviceBeanName);
        if (requestURI.endsWith("/add")) {
            T t = JSON.parseObject(JSON.toJSONString(params), claz);
            baseService.save(t);
            return R.ok();
        }else if(requestURI.endsWith("/listDict")){

            return R.ok(baseService.lambdaQuery().list());

        } else if (requestURI.endsWith("/list")) {
            Integer limit = getIntParam(request, "limit", 10);
            Integer offset = getIntParam(request, "offset", 0);
            List<T> list = baseService.lambdaQuery()
                    .last("limit " + offset + "," + limit)
                    .list();

            Long count = baseService.lambdaQuery()
                    .count();
            return Page.wrapper(count, list);
        }else if (requestURI.endsWith("/update")){
            T t = JSON.parseObject(JSON.toJSONString(params), claz);
            baseService.updateById(t);
            return R.ok();
        }else if (requestURI.endsWith("/delete")){
            String id = request.getParameter("id");
            baseService.removeById(id);
            return R.ok();
        } else if (requestURI.endsWith("/getById")) {
            String id = request.getParameter("id");
            T byId = baseService.getById(id);
            return R.ok(byId);
        }
        return R.failed("not implement api entrypoint");
    }


}
